package xyz.suancaiyu.eurekazuulclient.filter;


import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * 在Zuul中使用过滤器
 * <p>
 * 过滤规则:url中必须包含token参数,但不限定具体值.
 * <p>
 * 下面url不过滤:
 * <p>
 * http://localhost:5000/hiapi/hi?name=suancaiyu&token=888sdfa
 * <p>
 * 下面url:
 * <p>
 * http://localhost:5000/hiapi/hi?name=suancaiyu
 * <p>
 * 会返回: token is empty
 */
@Component
public class MyFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(MyFilter.class);

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        Object accessToken = request.getParameter("token");
        /*
        解除此处的注释,即可开启过滤token参数.

        if (accessToken == null) {
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            } catch (Exception ex) {
            }
            return null;
        }*/
        log.info("ok");
        return null;
    }
}
